package com.example.demo.utils;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Author chenhuiyu
 * @Date 2023/12/7
 */
public class ReadExcelUtil {
    public static void readExcel(String excelName, InputStream inputStream, int sheetIndex) throws IOException {

        if (excelName.endsWith(".xlsx")) {
            System.out.println("xlsx");
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(inputStream);
            XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(sheetIndex);
            int lastRowNum = xssfSheet.getLastRowNum();
            System.out.println("lastRowNum:" + lastRowNum);

            for (int i = 0; i <= lastRowNum; i++) {
                XSSFRow row = xssfSheet.getRow(i);
                short lastCellNum = row.getLastCellNum();
                System.out.print("lastCellNum:" + lastCellNum + " |");
                for (int j = 0; j < lastCellNum; j++) {
                    System.out.print(row.getCell(j) + "|");
                }
                System.out.println();
//                inputStream.close();
            }
        } else if (excelName.endsWith(".xls")) {
            System.out.println("xls");
            HSSFWorkbook hssfWorkbook = new HSSFWorkbook(inputStream);
            HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(sheetIndex);
            int lastRowNum = hssfSheet.getLastRowNum();
            System.out.println("lastRowNum:" + lastRowNum);

            for (int i = 0; i <= lastRowNum; i++) {
                HSSFRow row = hssfSheet.getRow(i);
                short lastCellNum = row.getLastCellNum();
                System.out.print("lastCellNum:" + lastCellNum + " |");
                for (int j = 0; j < lastCellNum; j++) {
                    if (row.getCell(j).toString().isEmpty()) {
                        System.out.print(null + "|");
                    } else {
                        System.out.print(row.getCell(j) + "|");
                    }
                }
                System.out.println();
            }
        }
    }
}
